package servlet;


import gameserver.AuthServerMain;
import gameserver.SocketServer;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import modle.Stadium;

import org.hibernate.Query;
import org.hibernate.Session;

import util.SessionFactory;


/**
 * 在加载项目时，启动socketserver监听所有的游戏房间端口
 * @author Administrator
 *
 */
public class StartSocketServlet extends HttpServlet {
	//public static ServletContext application;
	
	
	//public static int arr[] = {1991,1992,1993,1994,1995,1996,1997,1998,1999};
	public static ArrayList<SocketServer> socketServerList = new ArrayList<SocketServer>();
	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		for(SocketServer server:socketServerList)
			server.stopSocket();
		super.destroy();
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		
		 System.out.println("#################开始启动Socket授权服务");
		    new AuthServerMain().startServer();
		    System.out.println("#################开始启动Socket服务");
		
		Session session = SessionFactory.getSession();
		Query query = session.createQuery("from Stadium");
		List<Stadium> roomsList = query.list();
		int size = roomsList.size();
	//	application = this.getServletContext();
		System.out.println("init");
		
		for(int port = 1; port <= size; port++){
			
			try {
				SocketServer server = new SocketServer(1991+port);
				
				server.type = roomsList.get(port-1).getTableSetupMethod().charAt(0); //设置每个服务器的类型
				System.out.println("server.type= "+ port +" " + server.type);
				server.startSocket();
				socketServerList.add(server);
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("启动Socket失败！");
			}
		}
		
		
		
	}

}
